<?php

namespace app\admin\controller;

use think\Db;

class Coupon extends Common {
    /**
     * @return mixed
     */
    public function index() {
        $where = [];

        $search_name = input('param.name');
        $search_type = input('param.search');
        $this->assign('name', $search_name);
        $this->assign('search', $search_type);
        if ($search_name && $search_type) {
            if ($search_type == 'user_id') {
                $where['t1.' . $search_type] = $search_name;
            } else {
                $where['t1.' . $search_type] = ['like', "%$search_name%"];
            }
        }

        $start = input('start');
        $end   = input('end');
        $search_key   = input('search_key');
        $this->assign('start', $start);
        $this->assign('end', $end);
        $this->assign('search_key', $search_key);
        if ($start && $end) {
            $where['t1.' . $search_key] = ['between', [strtotime($start), strtotime($end)]];
        } elseif ($start && !$end) {
            $where['t1.' . $search_key] = ['egt', strtotime($start)];
        } elseif (!$start && $end) {
            $where['t1.' . $search_key] = ['elt', strtotime($end)];
        }

        $state = input('state');
        if ($state || $state === '0') {
            $this->assign('state', $state);
            $where['t1.state'] = $state;
        }

        $data = Db::name('user_coupon')
            ->alias('t1')
            ->join('user t2', 't1.user_id = t2.id', 'left')
            ->where($where)
            ->field('t1.*, t2.name username, t2.head_portrait')
            ->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item) {
                return $item;
            });

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }
}